import { defineStore } from "pinia";
import request from "@/utils/request";
import { ApiRes } from "@/types/data";
import { CartItem } from "@/types/cart";
import useStore from "..";

const useCartStore = defineStore("cart", {
  state() {
    return {
      list: [] as CartItem[],
    };
  },
  persist: {
    key: "rabbit-cart-78",
  },
  actions: {
    // 加入购物车
    async addCart(data: CartItem) {
      if (this.isLogin) {
        await request.post("/member/cart", {
          skuId: data.skuId,
          count: data.count,
        });
        this.getCartList();
      } else {
        // 1. 判断购物车列表中是否有该商品数据
        const goods = this.list.find((item) => item.skuId === data.skuId);
        if (goods) {
          goods.count += data.count;
        } else {
          this.list.unshift(data);
        }
      }
    },
    // 获取购物车列表
    async getCartList() {
      if (this.isLogin) {
        const res = await request.get<ApiRes<CartItem[]>>("/member/cart");
        this.list = res.data.result;
      } else {
        console.log("本地添加购物车");
      }
    },

    // 删除购物车数据
    async delCart(skuIds: string[]) {
      if (this.isLogin) {
        await request.delete("/member/cart", {
          data: {
            ids: skuIds,
          },
        });
        this.getCartList();
      } else {
        this.list = this.list.filter((item) => !skuIds.includes(item.skuId));
      }
    },

    // 修改购物车商品数据
    async updateCart(
      skuId: string,
      data: { selected?: boolean; count?: number }
    ) {
      if (this.isLogin) {
        await request.put(`/member/cart/${skuId}`, data);
        this.getCartList();
      } else {
        const sku = this.list.find((item) => item.skuId === skuId);
        if (data.count !== undefined) {
          sku!.count = data.count;
        }
        if (data.selected !== undefined) {
          sku!.selected = data.selected;
        }
      }
    },

    async updateCartAllSelected(isSelected:boolean) {
      if (this.isLogin) {
        await request.put("/member/cart/selected", {selected:isSelected});
        // 获取购物车列表
        this.getCartList();
      } else {
        this.list.forEach((item) => {
          item.selected = isSelected;
        });
      }
    },

    // 清空购物车
    clearCart() {
      this.list = [];
    },

    // 合并购物车
    async mergeLocalCart() {
      const data = this.list.map((item) => {
        return {
          count: item.count,
          selected: item.selected,
          skuId: item.skuId,
        };
      });
      await request.post("/member/cart/merge", data);
      this.getCartList();
    },
  },
  getters: {
    // 🔑登录状态
    isLogin(): boolean {
      const { user } = useStore();
      return !!user.profile.token;
    },
    // 有效商品
    effectiveList(): CartItem[] {
      return this.list.filter((item) => item.isEffective && item.stock > 0);
    },
    // 有效商品的总数量
    effectiveListCounts(): number {
      return this.effectiveList.reduce((sum, item) => sum + item.count, 0);
    },
    // 有效商品的总价格
    effectiveListPrice(): string {
      return this.effectiveList
        .reduce((sum, item) => sum + item.count * +item.nowPrice, 0)
        .toFixed(2);
    },

    // 计算商品是否全部选中
    isAllSelected(): boolean {
      return (
        this.effectiveList.length > 0 &&
        this.effectiveList.every((item) => {
          return item.selected;
        })
      );
    },
    // 已选择的列表
    selectedList(): CartItem[] {
      return this.effectiveList.filter((item) => item.selected);
    },
    // 已选择的商品总数
    selectedListCounts(): number {
      return this.selectedList.reduce((sum, item) => sum + item.count, 0);
    },
    // 已选择的列表总价
    selectedListPrice(): string {
      return this.selectedList
        .reduce((sum, item) => sum + item.count * Number(item.nowPrice), 0)
        .toFixed(2);
    },
  },
});

export default useCartStore;
